package kgc.crm.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import kgc.crm.dto.LeadsListDto;
import kgc.crm.enums.LabelTypeEnum;
import kgc.crm.mapper.*;
import kgc.crm.model.*;
import kgc.crm.service.IActionRecordService;
import kgc.crm.service.ILeadsService;
import kgc.crm.util.Constant;
import kgc.crm.util.EmptyChecker;
import kgc.crm.util.JWTManager;
import kgc.crm.util.ResultUtil;
import kgc.crm.vo.LeadsVo;
import lombok.Data;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

@Service("leadsServiceImpl")
@Slf4j
public class LeadsServiceImpl implements ILeadsService {
    @Autowired
    private LeadsMapper leadsMapper;
    @Autowired
    private ActionRecordMapper recordMapper;
    @Autowired
    private KgcCrmAdminFieldMapper fieldMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AdminFieldvMapper  adminFieldvMapper;
    @Autowired
    private IActionRecordService recordService;
//查看的方法
    //高级筛选
    @Override
    public ResponseEntity list(LeadsVo vo,String apiToken) {
        String fieldName = "";
        //当前登录的用户ID
        Long userId = JWTManager.getUserIDByToken(apiToken);
        if (!EmptyChecker.isEmpty(vo.getVo())) {
            KgcCrmAdminField field = fieldMapper.selectById(vo.getVo().getFieldId());
            fieldName = field.getFieldName();
        }
        LeadsListDto dto = new LeadsListDto(
                vo.getSearchVal(),(vo.getPageIndex()-1) * vo.getPageSize(),vo.getPageSize()
                ,vo.getVo(),userId,fieldName
        );
        return ResultUtil.success(leadsMapper.selectListByDto(dto));
    }

    @Override
    public ResponseEntity read(String batchId,String apiToken) {
        if (EmptyChecker.isEmpty(batchId)) {
            log.error("{线索查看模块：批次id不能为空}",batchId);
            return ResultUtil.error("参数不能为空");
        }
        QueryWrapper<Leads> qw = new QueryWrapper<>();
        qw.eq(Leads.COL_BATCH_ID,batchId);
        Leads leads = leadsMapper.selectOne(qw);
        User user = JWTManager.getUserByToken(apiToken);
        if (leads.getOwnerUserId() != user.getUserId()) {
            //执行数据库查询功能， 根据负责人 id 进行查询
            User owUser = userMapper.selectById(leads.getOwnerUserId());
            leads.setUserName(owUser.getUsername());
        }else {
            leads.setUserName(user.getUsername());
        }
        //查询所属行业
        AdminFieldv industry = adminFieldvMapper.selectById(leads.getIndustry());
        //查询线索来源
        AdminFieldv resource = adminFieldvMapper.selectById(leads.getLeadsResource());
        //查询客户级别
        AdminFieldv level = adminFieldvMapper.selectById(leads.getLeadsLevel());
        //整合所有数据
        JSONObject leadsJson = JSON.parseObject(JSON.toJSONString(leads));
        leadsJson.put("industry",industry);
        leadsJson.put("leadsResource",industry);
        leadsJson.put("leadsLevel",level);
        return ResultUtil.success(leadsJson);
    }

    @Override
    public ResponseEntity selectFieldList(Integer label) {
        //根据ID查询相关的自定义字段
        //定义wrapper
        QueryWrapper<KgcCrmAdminField> wq = new QueryWrapper<>();
        wq.eq(KgcCrmAdminField.COL_LABEL,label)
            .eq(KgcCrmAdminField.COL_FIELD_TYPE,0)
            .orderByDesc(KgcCrmAdminField.COL_SORTING);
        List<KgcCrmAdminField> fields = fieldMapper.selectList(wq);
        //先把fields把成json数组
        String jsonString = JSON.toJSONString(fields);
        JSONArray array = JSON.parseArray(jsonString);
        for (int i = 0; i < array.size(); i++) {
            JSONObject object = array.getJSONObject(i);
            Integer fieldId = object.getInteger("fieldId");
            QueryWrapper<AdminFieldv> wrapper = new QueryWrapper<>();
            wrapper.eq(AdminFieldv.COL_FIELD_ID,fieldId)
                    .orderByAsc(AdminFieldv.COL_ID);
            List<AdminFieldv> fieldvs = adminFieldvMapper.selectList(wrapper);
            object.put("fieldvs",fieldvs);
        }
        return ResultUtil.success(array);
    }

    @Override
    public ResponseEntity update(String apiToken,Leads leads) {
        QueryWrapper<Leads> wrapper = new QueryWrapper<>();
        if (EmptyChecker.isEmpty(leads)) {
            log.error("[更新线索信息] 更新内容最少要有一个值：{}",leads);
            return ResultUtil.error("参数不能为空");
        }
        if (EmptyChecker.isEmpty(leads.getLeadsId())) {
            log.error("[更新线索信息] ID不能为空：{}",leads);
            return ResultUtil.error("参数不能为空");
        }
        Long id = JWTManager.getUserIDByToken(apiToken);
        wrapper.eq(Leads.COL_LEADS_ID,leads.getLeadsId())
                .eq(Leads.COL_CREATE_USER_ID,id);
        int update = leadsMapper.update(leads, wrapper);
        if (update <= 0) {
            return ResultUtil.error("修改失败");
        }
        //修改成功，更新记录
        ActionRecord ar = new ActionRecord();
        ar.setCreateTime(new Date());
        ar.setTypes(Constant.LEADS_TYPE_NAME);
        ar.setActionId(leads.getLeadsId());
        ar.setCreateUserId(id);
        Object[] colm = getColm(leads);
        QueryWrapper<KgcCrmAdminField> qw = new QueryWrapper<>();
        qw.in(KgcCrmAdminField.COL_FIELD_NAME,colm);
        qw.select(KgcCrmAdminField.COL_NAME);
        List<KgcCrmAdminField> fields = fieldMapper.selectList(qw);
        StringBuffer buffer = new StringBuffer();
        buffer.append("修改了：");
        for (KgcCrmAdminField field : fields) {
            buffer.append(field.getName()+",");
        }
        ar.setContent(buffer.substring(0,buffer.length()));
        int insert = recordMapper.insert(ar);
        if (insert >= 0) {
            return ResultUtil.success("编辑成功");
        }
        return ResultUtil.error("编辑失败");
    }
    @SneakyThrows
    private Object[] getColm(Object o) {
        List<String> colmList = new ArrayList<>();
        Class<?> c = o.getClass();
        Field[] fields = c.getDeclaredFields();
        for (Field item : fields) {
            boolean present = item.isAnnotationPresent(TableField.class);
            if (!present)
                continue;
            //私有属性，让私有属性可以直接被操作
            item.setAccessible(true);
            Object val = item.get(o);
            if (val != null) {
                TableField table = item.getAnnotation(TableField.class);
                colmList.add(table.value());
            }
        }
        return colmList.toArray();
    }

    @Override
    @Transactional
    public ResponseEntity addLeads(Leads leads, String apiTOKEN,String types) {
        //线索名称不能为空
        if (EmptyChecker.isEmpty(leads)) {
            log.error("【添加线索模块】 Leads实体对象为空",leads);
            return ResultUtil.error("数据不能为空");
        }
        //判断名称不能为空
        if (EmptyChecker.isEmpty(leads.getLeadsName())) {
            log.error("【添加线索模块】线索名称为空",leads);
            return ResultUtil.error("线索名称不能为空");
        }
        //负责人 创建人 都是登陆者
        Long userId = JWTManager.getUserIDByToken(apiTOKEN);
        leads.setCreateUserId(userId);  //创建者id
        leads.setOwnerUserId(userId);  //负责人id
        leads.setFollowup(0);
        leads.setIsTransform(0);
        leads.setBatchId(System.currentTimeMillis()+"");
   //     leads.setCreateTime(new Date());
        int i = -1;
        try {
           i = leadsMapper.insert(leads);
            if (i < 0) {
                //i小于0  添加失败， 事务回滚
                TransactionAspectSupport.currentTransactionStatus()
                        .setRollbackOnly();
                log.error("【添加线索模块】线索添加失败",leads);
                return ResultUtil.error("线索添加失败");
                //真的添加失败，报错
            }
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus()
                    .setRollbackOnly();
            log.error("【添加线索模块】线索添加失败",e);
            return ResultUtil.error("线索添加失败");
            //过程中报错
        }
        //添加操作记录 构建ActionMapper
        if (!recordService.addActionRecord(userId,leads.getLeadsId(),"新建了线索", LabelTypeEnum.LEADS.getValue())) {
            //如果是false
            TransactionAspectSupport.currentTransactionStatus()
                    .setRollbackOnly();
            return ResultUtil.error("线索添加失败");
        }
        return ResultUtil.success("线索添加成功");
    }

    @Override
    public ResponseEntity recordSearch(Integer id, String apiToken) {
        if (EmptyChecker.isEmpty(id)) {
            log.error("【查询线索操作】 查询线索操作失败，线索id不能为空");
            return ResultUtil.error("参数不能为空");
        }
        Long token = JWTManager.getUserIDByToken(apiToken);
        QueryWrapper<ActionRecord> wrapper = new QueryWrapper<>();
        wrapper.eq(ActionRecord.COL_ACTION_ID,id)
                .eq(ActionRecord.COL_TYPES,Constant.LEADS_TYPE_NAME)
                .eq(ActionRecord.COL_CREATE_USER_ID,token)
                .orderByDesc(ActionRecord.COL_CREATE_TIME);
        List<ActionRecord> list = recordMapper.selectList(wrapper);
        return ResultUtil.success(list);
    }
}
